package com.example.demo.exception;

import com.example.demo.dto.ResponseDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;


/**
 * 说明：异常统一管理
 * <p>
 * #@ControllerAdvice
 * 增强Controller注解, 使用场景:
 * 1.全局异常处理
 * 2.全局数据绑定
 * 3.全局数据预处理
 * <p>
 *
 * @author 张垚
 * @see <a href="https://www.cnblogs.com/gdwkong/articles/8660002.html">8660002.html</a>
 */
@ControllerAdvice
@Slf4j
public class AllExceptionHandler {

    /**
     * 判断错误是否是已定义的已知错误，不是则由未知错误代替，同时记录在log中
     *
     * @param e Exception
     * @return JsonRespDto
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public ResponseEntity<ResponseDTO<String>> exceptionGet(Exception e) {
        String message = e.getMessage();
        log.error("接口调用异常: {}", message, e);
        return ResponseEntity.badRequest().body(ResponseDTO.error(400, e.getMessage()));
    }

}
